﻿using IdentityServer4.Events;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Identity;
using Naruto.MongoDB;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Authorization.Entitys.DTO;
using Authorization.Infrastructure;
using Authorization.Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
using Authorization.Entitys.Models;
using Authorization.Entitys.Model;

namespace Authorization.Application
{
    public class AccountApps
    {
        private readonly SignInManager<AuthorizationUser> signInManager;
        private readonly UserManager<AuthorizationUser> userManager;

        private readonly IEventService events;//id4触发的事件

        public AccountApps(SignInManager<AuthorizationUser> _signInManager, UserManager<AuthorizationUser> _userManager, IEventService _events)
        {
            signInManager = _signInManager;
            userManager = _userManager;
            events = _events;
        }

        public async Task<NarutoResult> Login(LoginDTO info)
        {
            if (info == null)
            {
                return new NarutoFailResult("参数错误");
            }
            if (info.userName.IsNullOrEmpty())
            {
                return new NarutoFailResult("用户名不能为空");
            }
            if (info.pswd.IsNullOrEmpty())
            {
                return new NarutoFailResult("密码不能为空");
            }
            //获取用户信息
            var user = await userManager.FindByNameAsync(info.userName);
            if (user == null)
            {
                return new NarutoFailResult("账号不存在!!!");
            }
            if (userManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, info.pswd) == PasswordVerificationResult.Failed)
            {
                return new NarutoFailResult("密码错误");
            }
            //密码登录
            var res = await signInManager.PasswordSignInAsync(info.userName, info.pswd, false, false);
            //成功跳转
            if (res.Succeeded)
            {
                //触发登录成功的事件
                await events.RaiseAsync(new UserLoginSuccessEvent(info.userName, user.Id, info.userName));
                return new NarutoSuccessResult("登录成功");
            }
            return new NarutoFailResult("登录失败");
        }


        /// <summary>
        /// 退出登录
        /// </summary>
        public async Task LoginOut()
        {
            await signInManager.SignOutAsync();//退出登录
        }

    }
}
